package com.easy.life.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.easy.life.common.AliyunOssConstant;
import com.easy.life.common.R;
import com.easy.life.service.OssService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {

    @Override
    public R uploadPictures(List<MultipartFile> files) {
        String endpoint = AliyunOssConstant.END_POINT;
        String accessKeyId = AliyunOssConstant.KEY_ID;
        String accessKeySecret = AliyunOssConstant.KEY_SECRET;
        String bucketName = AliyunOssConstant.BUCKET_NAME;
        try {
            OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            List<String> urls=new ArrayList<>();
            for (MultipartFile file : files) {
                InputStream inputStream = file.getInputStream();
                String fileName= UUID.randomUUID().toString().replace("-", "")
                        +file.getOriginalFilename();
                String filePath="picture/"+fileName;
                oss.putObject(bucketName,filePath,inputStream);
                String url="https://"+bucketName+'.'+endpoint+"/"+filePath;
                urls.add(url);
            }
            oss.shutdown();

            return R.ok().put("data",urls);
        }catch (Exception e){
            e.printStackTrace();
            return R.error("上传失败!");
        }
    }

    @Override
    public R uploadAvatar(MultipartFile file) {
        String endpoint = AliyunOssConstant.END_POINT;
        String accessKeyId = AliyunOssConstant.KEY_ID;
        String accessKeySecret = AliyunOssConstant.KEY_SECRET;
        String bucketName = AliyunOssConstant.BUCKET_NAME;
        try {
            OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            InputStream inputStream = file.getInputStream();
            String fileName= UUID.randomUUID().toString().replace("-", "")
                    +file.getOriginalFilename();
            String filePath="picture/"+fileName;
            oss.putObject(bucketName,filePath,inputStream);
            String url="https://"+bucketName+'.'+endpoint+"/"+filePath;
            oss.shutdown();
            return R.ok().put("data",url);
        }catch (Exception e){
            e.printStackTrace();
            return R.error("上传失败!");
        }

    }
}
